{
 "cells": [
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "8513604a50003dcf"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# PromptTemplate的使用\n",
    "\n",
    "1、PromptTemplate如何获取实例  (掌握，两种方式)\n",
    "\n",
    "2、两种特殊结构的使用 （部分提示词模板的使用(掌握)、组合提示词的使用）\n",
    "\n",
    "3、给变量赋值的两种方式(掌握)：format() / invoke()\n",
    "\n",
    "4、结合大模型的使用\n",
    "\n",
    "## 1、PromptTemplate如何获取实例\n",
    "\n",
    "方式1：使用构造方法的方式"
   ],
   "id": "4bc63929c7bd8a54"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:56:55.513500Z",
     "start_time": "2025-09-27T21:56:55.507952Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "#1、创建PromptTemplate的实例\n",
    "#参数中必须要指明：input_variables 、template\n",
    "prompt_template = PromptTemplate(\n",
    "    template=\"你是一个{role},你的名字叫{name}\",\n",
    "    input_variables=[\"role\",\"name\"]\n",
    ")\n",
    "\n",
    "# print(prompt_template)\n",
    "\n",
    "#2、填充实例中的变量。暂且使用format()\n",
    "prompt = prompt_template.format(role=\"人工智能专家\",name=\"小智\")\n",
    "\n",
    "print(prompt)"
   ],
   "id": "29914306542af39a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个人工智能专家,你的名字叫小智\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:59:30.289377Z",
     "start_time": "2025-09-27T21:59:30.283348Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"]\n",
    "\n",
    ")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "prompt_2 = template.format(product=\"笔记本电脑\", aspect1=\"处理速度\", aspect2=\"便携性\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)\n",
    "print(\"提示词2:\",prompt_2)"
   ],
   "id": "d5dfadd804446359",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n",
      "提示词2: 请评价笔记本电脑的优缺点，包括处理速度和便携性。\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式2：from_template() : 推荐！！",
   "id": "713b2f6fc3b791dd"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:03:39.469366Z",
     "start_time": "2025-09-27T22:03:39.464869Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "\n",
    "#1、创建PromptTemplate的实例\n",
    "prompt_template = PromptTemplate.from_template(template=\"你是一个{role},你的名字叫{name}\")\n",
    "\n",
    "# print(prompt_template)\n",
    "\n",
    "#2、填充实例中的变量。暂且使用format()\n",
    "prompt = prompt_template.format(role=\"人工智能专家\",name=\"小智\")\n",
    "\n",
    "print(prompt)"
   ],
   "id": "3b8f795ca708e8bd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个人工智能专家,你的名字叫小智\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:03:59.931941Z",
     "start_time": "2025-09-27T22:03:59.842784Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)"
   ],
   "id": "1fae9f7619f8ab9c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "如果提示词模板中不包含变量，则调用format()时，不需要传入参数！",
   "id": "d37972a353eec3a1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:04:45.318631Z",
     "start_time": "2025-09-27T22:04:45.312202Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1.导入相关的包\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 2.定义提示词模版对象\n",
    "text = \"\"\"\n",
    "Tell me a joke\n",
    "\"\"\"\n",
    "\n",
    "prompt_template = PromptTemplate.from_template(text)\n",
    "# 3.默认使用f-string进行格式化（返回格式好的字符串）\n",
    "prompt = prompt_template.format()\n",
    "print(prompt)"
   ],
   "id": "cba38a3f005a68ca",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Tell me a joke\n",
      "\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 2、 两种特殊结构的使用 （部分提示词模板的使用、组合提示词的使用）\n",
    "\n",
    "### 2.1 部分提示词模板的使用（重点）\n",
    "\n",
    "方式1： 在PromptTemplate的构造方法或from_template()方法内，使用partial_variables设置"
   ],
   "id": "367b9eabc7e1e58c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:06:32.098689Z",
     "start_time": "2025-09-27T22:06:32.091612Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    partial_variables={\"aspect1\":\"电池续航\"}\n",
    ")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\",aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)"
   ],
   "id": "26c83e01f4ef01fc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:08:20.698188Z",
     "start_time": "2025-09-27T22:08:20.692400Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    "    partial_variables={\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"}\n",
    ")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "6ce90140a7fc3644",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "方式2：调用方法partial()",
   "id": "ca02c3545614e43a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:11:14.317790Z",
     "start_time": "2025-09-27T22:11:14.312618Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    "    # partial_variables={\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"}\n",
    ")\n",
    "\n",
    "# partial()调用完以后，不会对调用者这个模板对象产生影响；而其返回值是一个新的模板\n",
    "template1 = template.partial(aspect1=\"电池续航\",aspect2=\"拍照质量\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template1.format(product=\"智能手机\")\n",
    "\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "72a62ddd837947cd",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:11:42.182852Z",
     "start_time": "2025-09-27T22:11:42.175767Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\",\n",
    "    input_variables=[\"product\", \"aspect1\", \"aspect2\"],\n",
    ").partial(aspect1=\"电池续航\",aspect2=\"拍照质量\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "edf84822d5af01f6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:12:11.937124Z",
     "start_time": "2025-09-27T22:12:11.931846Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = (PromptTemplate\n",
    "            .from_template(template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "            .partial(aspect1=\"电池续航\",aspect2=\"拍照质量\"))\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\")\n",
    "\n",
    "print(\"提示词1:\",prompt_1)"
   ],
   "id": "5264014de9b93608",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "提示词1: 请评价智能手机的优缺点，包括电池续航和拍照质量。\n"
     ]
    }
   ],
   "execution_count": 19
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "### 2.2 组合提示词的使用（了解）",
   "id": "dd700c68f64b05f6"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:13:12.454074Z",
     "start_time": "2025-09-27T22:13:12.450148Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "template = (\n",
    "    PromptTemplate.from_template(template = \"Tell me a joke about {topic}\")\n",
    "    + \", make it funny\"\n",
    "    + \"\\n\\nand in {language}\"\n",
    ")\n",
    "\n",
    "prompt = template.format(topic=\"sports\", language=\"spanish\")\n",
    "print(prompt)"
   ],
   "id": "aa5420d2532688b4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tell me a joke about sports, make it funny\n",
      "\n",
      "and in spanish\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## 3、给变量赋值的两种方式：format() / invoke()\n",
    "\n",
    "format() : 参数部分：给变量赋值;     返回值：str类型\n",
    "\n",
    "invoke() : 参数部分：使用的是字典;     返回值：PromptValue类型   ---推荐！\n",
    "\n",
    "\n",
    "举例：调用format()"
   ],
   "id": "540edbcdf2cec99f"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:14:08.127745Z",
     "start_time": "2025-09-27T22:14:08.121292Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "\n",
    "print(prompt_1)\n",
    "print(type(prompt_1))"
   ],
   "id": "a96bcefa96e3faef",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请评价智能手机的优缺点，包括电池续航和拍照质量。\n",
      "<class 'str'>\n"
     ]
    }
   ],
   "execution_count": 21
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例：调用invoke()",
   "id": "83eb75d69f9177e9"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:16:20.053035Z",
     "start_time": "2025-09-27T22:16:20.044900Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "#定义多变量模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "#使用模板生成提示词\n",
    "# prompt_1 = template.format(product=\"智能手机\", aspect1=\"电池续航\", aspect2=\"拍照质量\")\n",
    "prompt_1 = template.invoke(input={\"product\":\"智能手机\", \"aspect1\":\"电池续航\", \"aspect2\":\"拍照质量\"})\n",
    "\n",
    "print(prompt_1)\n",
    "print(type(prompt_1))  #返回值类型：PromptValue"
   ],
   "id": "a8805e437feb81aa",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text='请评价智能手机的优缺点，包括电池续航和拍照质量。'\n",
      "<class 'langchain_core.prompt_values.StringPromptValue'>\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 4、结合大模型的使用",
   "id": "e12e0b04448a0d16"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T22:17:36.386021Z",
     "start_time": "2025-09-27T22:17:29.933162Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "import dotenv\n",
    "\n",
    "#加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "\n",
    "os.environ[\"OPENAI_BASE_URL\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "\n",
    "\n",
    "# 获取对话模型：\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    max_tokens=500\n",
    ")\n",
    "\n",
    "\n",
    "# 生成提示词模板\n",
    "template = PromptTemplate.from_template(\n",
    "    template=\"请评价{product}的优缺点，包括{aspect1}和{aspect2}。\")\n",
    "\n",
    "# 给模板的变量赋值\n",
    "prompt = template.invoke(input={\"product\":\"智能手机\",\"aspect1\":\"电池续航\",\"aspect2\":\"拍照质量\"})\n",
    "\n",
    "# 调用大模型，将提示词传入\n",
    "response= chat_model.invoke(prompt)\n",
    "print(response)\n",
    "print(type(response))"
   ],
   "id": "697c7113c66c17d8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='智能手机作为现代通信和生活中不可或缺的设备，具有许多优缺点。以下是关于智能手机的一些主要优缺点，特别关注电池续航和拍照质量。\\n\\n### 优点\\n\\n1. **便携性**：\\n   - 智能手机小巧轻便，方便携带，可以随时随地进行通信、浏览信息和娱乐。\\n\\n2. **多功能性**：\\n   - 除了基本的通话和短信功能，智能手机集成了相机、导航、社交媒体、在线购物、办公应用等多种功能，能够满足多方面的需求。\\n\\n3. **拍照质量**：\\n   - 随着技术的发展，现代智能手机的摄像头质量显著提升，许多手机配备了多镜头系统，可以拍摄高质量的照片和视频，甚至在低光环境下也能表现良好。\\n\\n4. **应用生态**：\\n   - 丰富的应用商店提供多种应用程序，用户可以根据自己的需求下载和使用不同的APP，极大地丰富了智能手机的功能。\\n\\n5. **即时连接**：\\n   - 支持Wi-Fi、蓝牙和移动数据，在各种场合，用户可以快速连接互联网和设备，与他人保持联系。\\n\\n### 缺点\\n\\n1. **电池续航**：\\n   - 虽然一些智能手机电池容量较大，但由于高分辨率屏幕、处理器和持续使用的应用，许多智能手机的电池续航依然有限。用户可能需要频繁充电，特别是在重度使用的情况下。\\n\\n2. **价格**：\\n   - 高端智能手机往往价格昂贵，对于一些消费者来说，可能不容易承受。即便是入门级设备，随着技术的提升，价格也在逐渐上升。\\n\\n3. **软件更新和兼容性**：\\n   - 有些智能手机在发布后不久可能会停止接收软件更新，导致用户无法享受最新的功能和安全补丁。\\n\\n4. **过度依赖**：\\n   - 智能手机的多功能性容易导致用户对其产生过度依赖，可能会影响人际交往、注意力集中和心理健康。\\n\\n5. **拍照局限性**：\\n   - 尽管' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 500, 'prompt_tokens': 25, 'total_tokens': 525, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKXWOhA5hCMCDzS2eHk1dVwe8c4uC', 'service_tier': None, 'finish_reason': 'length', 'logprobs': None} id='run--c0cab9ba-9274-4b80-abe5-8feb302d980c-0' usage_metadata={'input_tokens': 25, 'output_tokens': 500, 'total_tokens': 525, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n",
      "<class 'langchain_core.messages.ai.AIMessage'>\n"
     ]
    }
   ],
   "execution_count": 23
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
